package cn.com.woxitech.dev.controller.mvc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.model.WeixinWebAccessToken;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@Controller
public class WeiXinMVCController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;
	@Autowired
	private Environment env;

	
	private String genWXAuthorizeUrl(String appid, String redirect_uri, String state, boolean scope_userinfo){
		
		String scope = "snsapi_base";
		if(scope_userinfo){
			scope = "snsapi_userinfo";
		}
		
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+  appid
				+ "&redirect_uri="
				+ redirect_uri
				+ "&response_type=code&scope="
				+ scope
				+ "&state="
				+ state 
				+ "#wechat_redirect";  
		return url;
	}
	
	@RequestMapping(value = "/wm/route", method = RequestMethod.GET)
	public ModelAndView route(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		String view = "";

		String code = request.getParameter("code");
		String state = request.getParameter("state"); //跳转到什么页面
		
		String serviceurlbase = env.getProperty("serviceurlbase");
		WeixinApiAccessToken fuwuapp = weixinService.getWeixinApiAccessTokenByName(Const.WX_FUWUORQIYE);
		String appid = fuwuapp.getAppid();
		
		WmUser wmUser = null;
		try {
			
			wmUser = this.weixinService.getWeiXinUser(code,fuwuapp);
			
			if(wmUser == null){
				String temp_redirect_uri = serviceurlbase + "/wm/route";
				String url = genWXAuthorizeUrl(appid,temp_redirect_uri, state, true);
				view = "redirect:"	+ url;
			}else{
				state = removeParams(state);
				view = "redirect:"+state+"?token="+EncryptionUtils.encode(wmUser.getUuid()+";"+System.currentTimeMillis());
			}
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(e.getMessage().equals("wxnotfound")){
				//通过code获取用户信息失败，
				//可能原因：code过期 , 解决策略：重新direct到route
				String temp_redirect_uri = serviceurlbase + "/wm/route";
				String url = genWXAuthorizeUrl(appid,temp_redirect_uri, state, true);
				view = "redirect:"	+ url;
			}
			
		}
		
		return new ModelAndView(view,map);
	}

	private String removeParams(String state) {
		// TODO Auto-generated method stub
		
		String url = state;
		
		int pos = url.indexOf("?");
		if(pos != -1){
			url = url.substring(0,pos);
		}
		return url;
	}
	
	
	

}
